package com.hxzy.module.auth.config.oauth;

import com.hxzy.framework.common.constant.AuthConstant;
import com.hxzy.module.auth.service.impl.UserDetailsImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述: OAUTH2服务
 *
 * @author tonneyyy
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;

    /**
     * 用户名认证接口(spring security规定的)
     */
    private final UserDetailsImpl userDetails;
    private final AuthenticationManager authenticationManager;

    /**
     * 自定义jwt增强内容
     */
    private final JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * 通过 ioc 构造函数注入
     * @param passwordEncoder
     * @param userDetails
     * @param authenticationManager
     * @param jwtTokenEnhancer
     */
    public Oauth2ServerConfig(PasswordEncoder passwordEncoder, UserDetailsImpl userDetails, AuthenticationManager authenticationManager, JwtTokenEnhancer jwtTokenEnhancer) {
        this.passwordEncoder = passwordEncoder;
        this.userDetails = userDetails;
        this.authenticationManager = authenticationManager;
        this.jwtTokenEnhancer = jwtTokenEnhancer;
    }

    /**
     * 获取jwt证书的内容
     * @return
     */
    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        //OAUTH令牌增强器,自定义添加一些额外信息
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(accessTokenConverter());
        enhancerChain.setTokenEnhancers(delegates);
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetails)
                .accessTokenConverter(accessTokenConverter())
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients();
    }

    /**
     * JWT有两个执行时机，
     * 一个是在用户认证成功时，对authentication进行加密，得到token发给用户，
     * 一个是当用户携带加密后的token访问服务时，JWT将token进行解码，再把token提取为authentication
     * 这两个时机的执行都是依靠JwtAccessTokenConverter来完成的
     * @return
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设定我们自己的RSA密钥
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    /**
     * 基于内存，配置OAuth授权请求值
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置后台管理client_id https://wx.com/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=http://juejin.im/callback&scope=read
                .withClient(AuthConstant.ADMIN_CLIENT_ID)
                .secret(passwordEncoder.encode(AuthConstant.ADMIN_CLIENT_SECRET))
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600 * 24)
                .refreshTokenValiditySeconds(3600 * 24 * 7)
                .and()
                .withClient(AuthConstant.ADMIN_SLAVE_CLIENT_ID)
                .secret(passwordEncoder.encode(AuthConstant.ADMIN_SLAVE_CLIENT_SECRET))
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600 * 24)
                .refreshTokenValiditySeconds(3600 * 24 * 7)
                .and()
                .withClient(AuthConstant.BACK_ADMIN_CLIENT_ID)
                .secret(passwordEncoder.encode(AuthConstant.BACK_ADMIN_CLIENT_SECRET))
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600 * 24)
                .refreshTokenValiditySeconds(3600 * 24 * 7);
    }

}
